package com.example.kekewaimaibao.rider.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.kekewaimaibao.core.constant.RestConstant;
import com.example.kekewaimaibao.core.utils.RegexUtil;
import com.example.kekewaimaibao.rider.model.RiderDO;
import com.example.kekewaimaibao.rider.service.IRiderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: xuxiang
 * @date: 2022/3/6 22:53 星期日
 * @description:
 * @version: 1.0
 */
@Slf4j
@RestController
@RequestMapping(RiderController.PATH)
@Api(tags = "骑手控制层")
@CrossOrigin
public class RiderController {
    public static final String PATH = RestConstant.VERSION_V1 + "/rider";

    @Autowired
    IRiderService riderService;

    /**
     * 建议弃用全表查询
     * @return
     */
    @ApiOperation(value = "所有骑手列表")
    @GetMapping("/list")
    public R list() {
        List<RiderDO> list = riderService.list(null);
        return R.ok(list);
    }

    /**
     * 可通过骑手名字模糊分页
     * @param current 当前页
     * @param limit 每页数据条数
     * @param riderDO 骑手信息
     * @return R
     */
    @ApiOperation(value = "分页查询骑手信息")
    @PostMapping("/page/{current}/{limit}")
    public R page(@PathVariable long current, @PathVariable long limit,
                  @RequestBody(required = false) RiderDO riderDO) {
        Page<RiderDO> page = new Page<>(current, limit);
        QueryWrapper<RiderDO> wrapper = null;
        if (ObjectUtil.isNotNull(riderDO)) {
            wrapper = new QueryWrapper<>();
            if (StrUtil.isNotBlank(riderDO.getRiderName())) {
                wrapper.like("rider_name", riderDO.getRiderName());
            }
        }
        riderService.page(page, wrapper);
        long total = page.getTotal();
        List<RiderDO> records = page.getRecords();
        Map map = new HashMap<>(4);
        map.put("current", current);
        map.put("limit", limit);
        map.put("total", total);
        map.put("records", records);
        return R.ok(map);
    }

    @ApiOperation(value = "添加骑手信息")
    @PostMapping("/save")
    public R save(@RequestBody RiderDO riderDO) {
        boolean flag = riderService.save(riderDO);
        if (flag) {
            return R.ok("后台添加骑手信息成功");
        } else {
            return R.failed("后台添加骑手信息失败");
        }
    }

    @ApiOperation(value = "删除骑手信息")
    @PostMapping("/remove/{id}")
    public R remove(@PathVariable Long id) {
        boolean flag = riderService.removeById(id);
        if (flag) {
            return R.ok("后台删除id为" + id +"的骑手信息成功");
        } else {
            return R.failed("后台删除骑手信息失败");
        }
    }

    @ApiOperation(value = "更新骑手信息")
    @PostMapping("update")
    public R update(@RequestBody RiderDO riderDO) {
        boolean flag = riderService.updateById(riderDO);
        if (flag) {
            return R.ok("后台更新id为" + riderDO.getRiderId() + "的骑手信息成功");
        } else {
            return R.failed("后台更新骑手信息失败");
        }
    }

    @ApiOperation(value = "批量删除骑手信息")
    @PostMapping("/remove-ids/{ids}")
    public R deleteBatchIds(@PathVariable("ids")String[] ids) {
        List<String> list = Arrays.asList(ids);
        boolean flag = riderService.removeByIds(list);
        if (flag) {
            return R.ok("批量删除骑手信息成功");
        } else {
            return R.failed("批量删除骑手信息失败");
        }
    }

    @ApiOperation(value = "通过id查找骑手信息")
    @GetMapping("/get-by-id/{id}")
    public R getByShopId(@PathVariable Long id) {
        RiderDO riderDO = riderService.getById(id);
        if (ObjectUtil.isNotNull(riderDO)) {
            return R.ok(riderDO);
        } else {
            return R.failed("未找到id为" + id + "的骑手");
        }
    }

    /**
     * 骑手通过骑手名字，手机号，密码进行注册
     * @param riderDO
     * @return
     */
    @ApiOperation(value = "骑手注册")
    @PostMapping("/register")
    public R register(@RequestBody RiderDO riderDO) {
        Map map = JSON.parseObject(JSON.toJSONString(riderDO), Map.class);
        // 判断注册信息不为空
        if (!StrUtil.isAllNotBlank((String) map.get("riderName"), (String) map.get("phone"),
                (String) map.get("password"))) {
            R result = R.failed("骑手某字段为空");
            result.setCode(520);
            return result;
        }
        // 判断表单字段是否合法
        // 昵称格式：限16个字符，支持中英文、数字、减号或下划线
        if (!RegexUtil.isNickName((String) map.get("riderName"))) {
            return R.failed("骑手姓名格式有误");
        }
        if (!RegexUtil.isPhone((String) map.get("phone"))) {
            return R.failed("骑手电话格式有误");
        }
        if (!RegexUtil.isPassword((String) map.get("password"))) {
            return R.failed("骑手密码格式有误");
        }
        boolean flag = riderService.save(riderDO);
        if (flag) {
            R result = new R();
            result.setCode(200);
            result.setMsg("骑手注册成功");
            return result;
        } else {
            R result = R.failed("骑手注册失败");
            result.setCode(520);
            return result;
        }
    }

    /**
     * 通过手机号，密码进行登录
     * @param riderDO
     * @return
     */
    @ApiOperation(value = "骑手登录")
    @PostMapping("/login")
    public R login(@RequestBody RiderDO riderDO) {
        String phone = riderDO.getPhone();
        String password = riderDO.getPassword();
        if (!RegexUtil.isPhone(phone)) {
            log.info("手机号格式有误 ---> {}", phone);
            return R.failed("手机号格式有误 ---> " + phone);
        }
        if (!RegexUtil.isPassword(password)) {
            log.info("密码格式有误 ---> {}", password);
            return R.failed("密码格式有误(限16个字符，支持英文、数字、减号或下划线) ---> " + password);
        }

        QueryWrapper<RiderDO> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone);
        riderDO = riderService.getOne(wrapper);
        if (ObjectUtil.isNull(riderDO)) {
            return R.failed("手机号输入错误");
        }
        if (!password.equals(riderDO.getPassword())) {
            return R.failed("密码输入错误");
        } else {
            Map<String, Object> map = JSON.parseObject(JSON.toJSONString(riderDO), Map.class);
            R result = new R();
            result.setMsg("登录成功");
            result.setData(map);
            return result;
        }
    }

    /**
     * 通过手机号进行重置密码（关于验证码的事由，可以使用第三方的短信业务）
     * @param riderDO
     * @return
     */
    @ApiOperation(value = "骑手忘记密码")
    @PostMapping("/reset")
    public R resetPassword(@RequestBody RiderDO riderDO) {
        String phone = riderDO.getPhone();
        String password = riderDO.getPassword();

        if (!RegexUtil.isPhone(phone)) {
            log.info("手机号格式有误 ---> {}", phone);
            R result = R.failed("手机号格式有误 ---> " + phone);
            result.setCode(520);
            return result;
        }
        if (!RegexUtil.isPassword(password)) {
            log.info("密码格式有误 ---> {}", password);
            R result = R.failed("密码格式有误(限16个字符，支持英文、数字、减号或下划线) ---> " + password);
            result.setCode(520);
            return result;
        }

        UpdateWrapper<RiderDO> wrapper = new UpdateWrapper<>();
        wrapper.eq("phone", phone);
        wrapper.set("password", password);
        boolean flag = riderService.update(wrapper);
        if (flag) {
            R result = new R();
            result.setMsg("密码重置成功");
            result.setCode(200);
            return result;
        } else {
            R result = R.failed("密码重置失败");
            result.setCode(520);
            return result;
        }
    }

    /**
     * 骑手通过手机号修改密码（后端没有对密码进行与原密码是否相等做校验）
     * @param riderDO
     * @return
     */
    @ApiOperation(value = "骑手修改密码")
    @PostMapping("change-password")
    public R changePassword(@RequestBody RiderDO riderDO) {
        if (RegexUtil.isPassword(riderDO.getPassword())) {
            R result = new R();
            result.setCode(520);
            return R.failed("密码格式错误");
        }
        UpdateWrapper<RiderDO> wrapper = new UpdateWrapper<>();
        wrapper.eq("phone", riderDO.getPhone());
        boolean flag = riderService.update(riderDO, wrapper);
        if (flag) {
            R result = new R();
            result.setMsg("修改密码成功");
            result.setCode(200);
            return result;
        } else {
            R result = R.failed("修改密码失败");
            result.setCode(520);
            return result;
        }
    }

    // 骑手端的数据看板功能（放到了DeliverController下，方便使用）
}
